﻿using System;
using System.Collections.Generic;
using Sapit.Helpers;

namespace Sapit.Base
{
    public abstract class CacheBase<T>
    {
        private static Dictionary<Invocation, TimedValue<T>> cachedInvocations = new Dictionary<Invocation, TimedValue<T>>();

        protected static void CacheInvocationValue(Invocation invocation, T value)
        {
            if (cachedInvocations.ContainsKey(invocation))
            {
                RemoveInvocationFromCache(invocation);
            }

            cachedInvocations.Add(invocation, new TimedValue<T>() { Value = value, When = DateTime.Now });
        }

        protected static bool IsInvocationValidInCache(Invocation invocation, int cacheSeconds)
        {
            return
                (cachedInvocations.ContainsKey(invocation) &&
                DateTime.Now < cachedInvocations[invocation].When.AddSeconds(cacheSeconds));
        }

        protected static T GetCachedValue(Invocation invocation)
        {
            return cachedInvocations[invocation].Value;
        }

        protected static void RemoveInvocationFromCache(Invocation invocation)
        {
            cachedInvocations.Remove(invocation);
        }
    }
}
